from pydantic import BaseModel, constr
from datetime import datetime
from typing import List, Optional
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base


class User(BaseModel):
    id: int  # 必填字段
    name: str = 'John Snow'  # 有默认值，选填插件
    signup_ts: Optional[datetime] = None
    friends: List[int] = []  # 列表中元素是int类型或者可以直接转换成int类型


external_data = {
    "id": "123",
    "signup_ts": '2022-12-22 12:22',
    "friends": [1, 5, "3"]

}

user = User(**external_data)
print(user.id, user.friends)
print(repr(user.signup_ts))
print(user.dict())

Base = declarative_base()


class CompanyOrm(Base):
    __tablename__ = 'companies'
    id = Column(Integer, primary_key=True, nullable=False)
    public_key = Column(String(20), index=True, nullable=False)
    name = Column(String(63), unique=True)
    domains = Column(ARRAY(String(255)))


class CompanyMode(BaseModel):
    id: int
    public_key: constr(max_length=20)
    name: constr(max_length=63)
    domains: List[constr(max_length=255)]

    class Config:
        orm_mode = True


co_orm = CompanyOrm(
    id=123,
    public_key='foo',
    name='Test',
    domains=['examp;e,com', 'imocc.com']
)

print(CompanyMode.from_orm(co_orm))
